﻿using System;
using System.Linq;
using System.Windows;
using LaunchPad.Core.Controls.Tracks.CanvasVirtualization;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Collections.Generic;

namespace LaunchPad.Core.Controls.Tracks
{

    public class VirtualSnippet : IVirtualChild
    {
        public VirtualSnippet() { }

        public VirtualSnippet(double position, double width, float[] samples) :
            this(position, width, samples, new SolidColorBrush(Colors.Black))
        {
        }


        public VirtualSnippet(double position, double width, float[] samples, Brush brush)
        {
            Position = position;
            Width = width;
            Brush = brush;

            double xscale = width / samples.Length;

            FirstSample = new Point(0, transformValue(samples[0]));
            Samples = new List<Point>();
            for (int i = 1; i < samples.Length; i++)
                Samples.Add(new Point(i * xscale, transformValue(samples[i])));
        }

        private static float transformValue(float value)
        {
            return value * 75 + 50;
        }

        public double Position { get; private set; }
        public double Width { get; private set; }
        public Point FirstSample { get; private set; }
        public List<Point> Samples { get; private set; }
        public VirtualSnippet Previous { get; private set; }
        public Brush Brush { get; private set; }

        UIElement _visual;

        public System.Windows.Rect Bounds
        {
            get 
            {
                return new Rect(Position, 0, Width, 100);
            }
        }

        public event EventHandler BoundsChanged;

        public System.Windows.UIElement Visual
        {
            get { return _visual; }
        }

        public System.Windows.UIElement CreateVisual(VirtualCanvas parent)
        {
            StreamGeometry geometry = new StreamGeometry();

            using (StreamGeometryContext ctx = geometry.Open())
            {
                ctx.BeginFigure(FirstSample, false, false);
                ctx.PolyLineTo(Samples, true, false);
            }

            geometry.Freeze();

            Path p = new Path();
            p.Data = geometry;
            p.Stroke = Brush;
            p.StrokeThickness = 0.2;
            p.Stroke.Freeze();

            _visual = p;

            return _visual;
        }

        public void DisposeVisual()
        {
            _visual = null;
        }
    }
}
